<template>
    <div class="login">
        <el-carousel :interval="2000" arrow="always" height="100%" style="width: 100%;height: 100%;">
            <el-carousel-item v-for="item in bgArr" :key="item">
                <img :src="item" style="width: 100%;height: 100%">
            </el-carousel-item>
        </el-carousel>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <!-- <h3 class="title">办公OA系统</h3> -->
            <div  v-if="loginModel == 2">
                <div class="login_header">
                <div class="header_left">扫码登录</div>
                <div class="header_right" @click="modelChange(1)">使用账号登录</div>
                </div>
                <div class="login_conts">
                <canvas @click="qrCodeRefres" id="QRCode_header" style="width: 155px;height: 155px;"></canvas>
                </div>
                <div class="login_footer">
                <!-- 扫一扫更方便 -->
                </div>
            </div>
            <div v-else>
                <div class="genggaimima flex_zhcenter" v-if="loginModel == 3">更改密码</div>
                <img v-if="loginModel != 3"
                @click="modelChange(2)"
                class="login_qhLOginModel" src="@/assets/images/qhlogin.png" >
                <el-tabs v-model="activeName" v-if="loginModel != 3" @tab-click="chongzhiForm">
                    <el-tab-pane label="账号登录" name="1"></el-tab-pane>
                    <el-tab-pane label="短信登录" name="2"></el-tab-pane>
                </el-tabs>
                <div v-if="activeName == 1 && loginModel == 1">
                    <el-form-item prop="username">
                        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
                            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="loginForm.password" type="password" show-password auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
                            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="code" v-if="captchaOnOff">
                        <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
                            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
                        </el-input>
                        <div class="login-code">
                            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
                        </div>
                    </el-form-item>
                    <el-form-item style="margin:0px 0px 25px 0px;">
                        <div class="flex_hcneter_bet">
                        <el-checkbox v-model="loginForm.rememberMe" >记住密码</el-checkbox>
                        <el-link type="primary" :underline="false" @click="modelChange(3)">忘记密码</el-link>
                        </div>
                    </el-form-item>
                </div>
                <div v-if="activeName == 2 || loginModel == 3">
                    <el-form-item prop="phone">
                        <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号" >
                            <template slot="prepend"><i class="el-icon-phone"></i></template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="smsCode">
                        <div class="flex_hcneter">
                            <el-input v-model="loginForm.code" type="text" class="flex_flex" auto-complete="off" placeholder="验证码" >
                                <template slot="prepend"><i class="el-icon-lock"></i></template>
                            </el-input>
                            <div class="yanzheng_block flex_zhcenter" @click="hqSmsFunc"> {{smsTitle}} </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="newPwd" v-if="loginModel == 3">
                        <el-input v-model="loginForm.newPwd" type="text" auto-complete="off" placeholder="新密码" show-password>
                            <template slot="prepend"><i class="el-icon-lock"></i></template>
                        </el-input>
                    </el-form-item>
                </div>
                <div v-if="activeName == 2 && loginModel == 1">
                    <el-form-item style="margin:0px 0px 25px 0px;">
                        <div class="flex_hcneter_bet">
                            <div class="" style="width:10px;"></div>
                            <el-link type="primary" :underline="false" @click="modelChange(3)">忘记密码</el-link>
                        </div>
                    </el-form-item>
                </div>
                <div v-if="loginModel == 3">
                    <el-form-item style="width:100%;" >
                        <el-button
                        :loading="loading"
                        size="medium"
                        type="primary"
                        style="width:100%;"
                        @click.native.prevent="handleUpdatePwd"
                        >更改密码</el-button>
                    </el-form-item>
                    <el-form-item style="margin-top:25px;">
                        <div class="flex_zhcenter">
                            <el-link type="primary"  :underline="false" @click="modelChange(1)">去登陆</el-link>
                        </div>
                    </el-form-item>
                </div>
                <el-form-item style="width:100%;" v-else>
                    <el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </el-button>
                    <!--  
                    <div style="float: right;" v-if="register">
                        <router-link class="link-type" :to="'/register'">立即注册</router-link>
                    </div>
                    -->
                </el-form-item>
            </div>
            
        </el-form>
        <!--  底部  -->
        <div class="el-login-footer">
            <span>Copyright © 2024-2026 jinxiang.com All Rights Reserved.</span>
        </div>
    </div>
</template>

<script>
import {getCodeImg,queryCompanyTenant,smsSend,qrCodeLogin,forgetPwd,} from "@/api/login";
import { createCode,getCodeInfo } from "@/api/other_xiangmu";
import Cookies from "js-cookie";
import {encrypt, decrypt} from '@/utils/jsencrypt'
import QRCode from 'qrcode';
import { isvalidPhone,validateMobile } from '@/utils/validate'
export default {
    name: "Login",
    data() {
        return {
            activeName:'1',
            loginModel:1,//登录模式 1普通登录2二维码登录3忘记密码
            ticket:'',
            ticketTime:'',//定时器
            ticketTime1:'',//计时器
            smsTitle:'获取验证码',//验证码标题
            smsFlag:null,//验证码定时器
            bgArr:[
                // require("@/assets/images/bg/bg-img-oa.jpg"),
                // require("@/assets/images/bg/7.jpg"),
                // require("@/assets/images/bg/6.jpg"),
                // require("@/assets/images/bg/5.jpg"),
                // require("@/assets/images/bg/4.jpg"),
                // require("@/assets/images/bg/3.jpg"),
                // require("@/assets/images/bg/2.jpg"),
                // require("@/assets/images/bg/1.jpg"),
                // require("@/assets/images/bg/bg-img-7.jpg"),
                // require("@/assets/images/bg/bg-img-6.jpg"),
                require("@/assets/images/bg/bg-img-5.jpg"),
                // require("@/assets/images/bg/bg-img-4.jpg"),
                // require("@/assets/images/bg/bg-img-3.jpg"),
                // require("@/assets/images/bg/bg-img-1.jpg"),

            ],
            codeUrl: "",
            companyName:"",
            options:[],
            searchLoading:false,
            loginForm: {
                tenantName: "锦翔信息科技有限公司",
                username: "",
                password: "",
                rememberMe: false,
                code: "",
                uuid: ""
            },
            loginRules: {
                tenantName: [
                    {required: true, trigger: "blur", message: "请输入需要登录的公司"}
                ],
                username: [
                    {required: true, trigger: "blur", message: "请输入您的账号"}
                ],
                password: [
                    {required: true, trigger: "blur", message: "请输入您的密码"}
                ],
                code: [{required: true, trigger: "change", message: "请输入验证码"}],
                phone: [
                    { required: true, message: "手机号不能为空", trigger: "blur" },
                    { validator: validateMobile.bind(this), trigger: 'blur' },
                ],
                newPwd: [{ required: true, trigger: "change", message: "请输入新密码" }],
            },
            loading: false,
            // 验证码开关
            captchaOnOff: true,
            // 注册开关
            register: true,
            redirect: undefined,
        };
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect;
            },
            immediate: true
        }
    },
    created() {
        this.getCode();
        this.getCookie();
        //this.searchCompanyTenant();
    },
    destroyed(){
      if(this.ticketTime) clearInterval(this.ticketTime)
      if(this.ticketTime1) clearTimeout(this.ticketTime1)
      if(this.smsFlag) clearInterval(this.smsFlag)
    },
    methods: {
        hqSmsFunc(){//获取验证码
            if(this.smsTitle == '获取验证码' || this.smsTitle == '重新获取验证码') {
            this.smsFunc()
            }
        },
        async smsSend(){//获取手机验证码
            let res = await smsSend({phone:this.loginForm.phone})
        },
        smsFunc(){
            if(!this.loginForm.phone || !isvalidPhone(this.loginForm.phone)) return this.$modal.msgError("请输入正确手机号")
            this.smsSend()
            if(this.smsFlag) clearInterval(this.smsFlag)
            this.smsTitle = 59
            this.smsFlag = setInterval(()=>{
            this.smsTitle -= 1
            if(this.smsTitle == 0) {
                clearInterval(this.smsFlag)
                this.smsTitle = '重新获取验证码'
            }
            },1000)
        },
        //二维码刷新
        qrCodeRefres(){
            this.createCode()
        },
        createCode(){//创建二维码
            createCode().then(res => {
                let data = res.data || ''
                let strList = data ? data.split('/') : []
                // this.qrcodeImg = data.url
                this.ticketCode = strList.length ? strList[strList.length - 1] : ''
                this.getQRCode(data)
                if(this.ticketTime) clearInterval(this.ticketTime)
                this.ticketTime = setInterval(()=>{
                    this.getCodeInfo()
                },1000)
                if(this.ticketTime1) clearTimeout(this.ticketTime1)
                this.ticketTime1 = setTimeout(()=>{
                    if(this.ticketTime) clearInterval(this.ticketTime)
                },60000)
            });
        },
        getCodeInfo(row){//轮询查看二维码状态
            getCodeInfo({code:this.ticketCode}).then(response => {
                let data  = response.data || {}
                let status = data.status
                let code = data.code
                let token = data.token
                if(status == 2 && token){
                clearInterval(this.ticketTime)
                this.qrCodeLogin(token)
                }
            }).catch(error=>{
                if(this.ticketTime) clearInterval(this.ticketTime)
                if(this.ticketTime1) clearTimeout(this.ticketTime1)
            });
        },
        async qrCodeLogin(token){//二维码登录
            qrCodeLogin({token}).then(response => {
                let data = response.data || {}
                this.$store.dispatch("LoginQrcode", data).then(() => {
                    this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
                }).catch(() => {
                    this.loading = false;
                    if (this.captchaEnabled) {
                    this.getCode();
                    }
                });
            });
        },
        //生成二维码
        getQRCode(url){
            console.log(url)
            let opts = {
            errorCorrectionLevel: "L", //容错级别
            type: "image/png", //生成的二维码类型
            quality: 0.6, //二维码质量
            margin: 0, //二维码留白边距
            width: 155, //宽
            height: 155, //高
            color: {
                dark: "#333333", //前景色
                light: "#fff", //背景色
            },
            };
            let msg = document.getElementById("QRCode_header");
            // 将获取到的数据(val)画到msg(canvas)上
            QRCode.toCanvas(msg, url, opts, function (error) {
                console.log(error)
                if (error) {
                console.log("二维码加载失败", error);
                //this.$message.error("二维码加载失败");
                }
            });
        },
        modelChange(e){//切换登录模式
            if(e == 1 && this.loginModel == 3) this.activeName = '1'
            this.loginModel = e
            if(e == 2){
                this.$nextTick(()=>{
                    // this.getQRCode('https://sy.ipark.vip/x/06EH');
                    this.createCode()
                })
            }
            this.chongzhiForm()
        },
        searchCompanyTenant(){
                this.searchLoading = true;
                let data = {
                    status:0
                }
                queryCompanyTenant(data).then(res=>{
                    this.searchLoading = false;
                    this.options = res.data;
                })
        },
        getCode() {
            getCodeImg().then(res => {
                this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
                if (this.captchaOnOff) {
                    this.codeUrl = "data:image/gif;base64," + res.img;
                    this.loginForm.uuid = res.uuid;
                }
            });
        },
        getCookie() {
            const tenantName = Cookies.get("tenantName");
            const username = Cookies.get("username");
            const password = Cookies.get("password");
            const rememberMe = Cookies.get('rememberMe')
            this.loginForm = {
                tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName,
                username: username === undefined ? this.loginForm.username : username,
                password: password === undefined ? this.loginForm.password : decrypt(password),
                rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
            };
        },
        handleUpdatePwd(){//修改密码
            this.$refs.loginForm.validate(async valid => {
            if (valid) {
                this.loading = true;
                forgetPwd(this.loginForm).then(response => {
                    this.loginModel = 1
                    this.activeName = '1'
                    this.$modal.msgSuccess("操作成功")
                    this.loading = false;
                    this.chongzhiForm()
                }).catch(()=>{this.loading = false; });
            }
            });
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    if(this.activeName == 2 && this.loginModel == 1) {
                        this.$store.dispatch("PhoneLogin", this.loginForm).then(() => {
                            this.loading = false;
                            this.$router.push({path: this.redirect || "/"}).catch(() => { });
                        }).catch(() => { this.loading = false; });
                    }else{
                        if (this.loginForm.rememberMe) {
                            Cookies.set("tenantName", this.loginForm.tenantName, {expires: 30});
                            Cookies.set("username", this.loginForm.username, {expires: 30});
                            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
                            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
                        } else {
                            Cookies.remove("tenantName");
                            Cookies.remove("username");
                            Cookies.remove("password");
                            Cookies.remove('rememberMe');
                        }

                        let loginInfo = {
                            username:this.loginForm.username,
                            password:this.loginForm.password,
                            code:this.loginForm.code,
                            uuid:this.loginForm.uuid
                        }

                        this.$store.dispatch("Login", loginInfo).then(() => {
                            this.loading = false;
                            this.$router.push({path: this.redirect || "/"}).catch(() => { });
                        }).catch(() => {
                            this.loading = false;
                            if (this.captchaOnOff) {
                                this.getCode();
                            }
                        });
                    }
                    
                }
            });
        },
        chongzhiForm(){
            let loginForm = {...this.loginForm}
            loginForm.code = null
            this.loginForm = {...loginForm}
        },
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-size: cover;
}
.genggaimima{
  border-bottom: 1px solid #E4E7ED;font-size: 14px;padding: 10px 0;margin-bottom: 30px;
}
.yanzheng_block{
  padding: 0px 10px;border: 1px solid #F1F1F1;border-radius: 5px;margin-left: 10px;cursor: pointer;
  color: #C0C4CC;box-sizing: border-box;min-width: 92px;
}
.wangjimima{color: #1890FF;cursor: pointer;font-weight: bold;}

.title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
}

.login-form {
    position: absolute;
    top: 150px;
    z-index: 999;
    border:1px solid #dddddd;
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
    .login_header{
      display:flex;margin-bottom: 40px;
      align-items: center;justify-content: space-between;
      .header_left{font-size: 24px;}
      .header_right{font-size: 17px;color: #0593E0;cursor: pointer;}
    }
    .login_conts{display:flex;align-items: center;justify-content: center;}
    .login_footer{font-size: 17px;margin-top: 30px;padding-bottom: 54px;text-align: center;}
    .login_qhLOginModel{
      position:absolute;cursor: pointer;
      top: 0;right: 0;width: 52px; height: 52px
    }
    .el-input {
        height: 38px;

        input {
            height: 38px;
        }
    }

    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
    }
}

.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}

.login-code {
    width: 33%;
    height: 38px;
    float: right;

    img {
        cursor: pointer;
        vertical-align: middle;
    }
}

.el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}

.login-code-img {
    height: 38px;
}
</style>
